using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Pixysoft.IO
{
    //Don't include <CRLF>
    public class StreamLineReader
    {
        private Stream m_StrmSource = null;

        public StreamLineReader(Stream strmSource)
        {
            if (strmSource == null)
                throw new Exception("missing stream in StraemLineReader.");

            m_StrmSource = strmSource;
        }

        public byte[] ReadLine()
        {
            List<byte> lineBuf = new List<byte>();

            byte prevByte = 0;

            int currByteInt = m_StrmSource.ReadByte();

            while (currByteInt > -1)
            {
                lineBuf.Add((byte)currByteInt);

                // Line found

                if ((prevByte == (byte)'\r' && (byte)currByteInt == (byte)'\n'))
                {
                    byte[] retVal = new byte[lineBuf.Count - 2];    // Remove <CRLF> 

                    lineBuf.CopyTo(0, retVal, 0, lineBuf.Count - 2);

                    return retVal;
                }

                // Store byte

                prevByte = (byte)currByteInt;

                // Read next byte

                currByteInt = m_StrmSource.ReadByte();
            }

            // Line isn't terminated with <CRLF> and has some chars left, return them.

            if (lineBuf.Count > 0)
            {
                byte[] retVal = new byte[lineBuf.Count];

                lineBuf.CopyTo(0, retVal, 0, lineBuf.Count);

                return retVal;
            }

            return null;
        }



        public bool HasMore
        {
            get { return m_StrmSource.Position > m_StrmSource.Length; }
        }



    }
}
